package com.aaa.zs.filter;

import com.aaa.zs.servie.UserService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @fileName:LoginFilter
 * @description:
 * @author:忆尘
 * @createTime:2020/11/13 22:32
 * @version:1.0.0
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private UserService userService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入了登录滤器。。。");
        //使用zuul包中提供请求上下文类获取请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request =currentContext.getRequest();
        //获取response对象
        HttpServletResponse response = currentContext.getResponse();
        //获取请求地址
        String requestURI = request.getRequestURI();
        System.out.println(requestURI+"地址");
        //判断是否为登录请求 判断是否带有token 在判断是否正确
        String accessToken = request.getParameter("accessToken");
        if(requestURI.contains("/sso/SsoController/userLogin")||(!StringUtils.isEmpty(accessToken))&&(userService.checkToken(accessToken))){
            //放行
            currentContext.setSendZuulResponse(true);
            /*request.getRequestURL();
            request.getRequestDispatcher("/a.jsp").forward(accessToken,accessToken);*/
        }else {
            //拦截
            currentContext.setSendZuulResponse(false);
            try {
                response.getWriter().print("nologin");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
